package com.jjiang.bbmall.order.listener;

import com.jjiang.bbmall.order.entity.OrderEntity;
import com.jjiang.bbmall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@RabbitListener(queues = "order.release.order.queue")
@Service
public class OrderCloseListener {
    @Autowired
    OrderService orderService;

    @RabbitHandler
    public void listener(OrderEntity entity, Channel channel, Message message) throws IOException {
        System.out.println("收到过期订单信息，准备关闭订单。订单号：" + entity.getOrderSn());
        Boolean retry = true;
        try {
            retry = orderService.closeOrder(entity);
        } catch (Exception e) {
            // 有异常，消费失败，需要重试
        }
        if (retry) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        } else {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
